unit DBFixMainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IPEdit, StdCtrls, ComCtrls, TcpFileClient, IdTCPClient;

type
  TForm1 = class(TForm)
    ServerIp: TIPEdit;
    Label1: TLabel;
    Label2: TLabel;
    Button1: TButton;
    pbView: TProgressBar;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    procedure OnTcpCopy(AStatus: string;
                        AAllSize, ACurSize,
                        AFileAllSize, AFileCurSize: Int64;
                        ASpeed: Double;
                        ARemainTime: TDateTime);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses ProtocolUnit;

{$R *.dfm}

function CheckTcpServer(AHost: string; APort: Integer; AWait: Integer = 200): Boolean;
var
  cli: TIdTCPClient;
  i: Integer;
begin
  Result := False;
  cli := TIdTCPClient.Create(nil);
  try
    cli.Host := AHost;
    cli.Port := APort;

    i := 0;
    repeat
      try
        cli.Connect(AWait);
        Application.ProcessMessages;
        if cli.Connected then
        begin
          Result := True;
          Break;
        end;
      except

      end;
      Inc(i);
    until i > 5;

  finally
    cli.Disconnect;
    cli.Free;
  end;
  
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Ip: string;
begin
  Ip := ServerIp.IPString;
  if Ip = '0.0.0.0' then
  begin
    Application.MessageBox('Please set server IP first', 'Prompt', MB_ICONINFORMATION);
    Exit;
  end;

  if not CheckTcpServer(Ip, TcpFilePort) then
  begin
    Application.MessageBox('Can not connect to server', 'prompt', MB_ICONINFORMATION);
    Exit;
  end;
  
  with TTcpCompareClient.Create('Client\Data', ExtractFilePath(ParamStr(0)) + 'Data',
                                  Ip, TcpFilePort,
                                  '', '', True, True, True) do
    try
      OnCompareCopyEvent := OnTcpCopy;
      DoStart;
    finally
      Free;
    end;

  Application.MessageBox('Fix finished', 'Prompt', MB_ICONINFORMATION);
end;

procedure TForm1.OnTcpCopy(AStatus: string; AAllSize, ACurSize,
  AFileAllSize, AFileCurSize: Int64; ASpeed: Double;
  ARemainTime: TDateTime);
begin
  pbView.Min := 0;
  pbView.Max := Trunc(AAllSize / 1024);
  pbView.Position := Trunc(ACurSize / 1024);
end;

end.
